
/**
 * Controller of order Repay form that may select payment method
 */
OrderRepayController = Class.create();
OrderRepayController.prototype = {
    _canSubmitOrder : false,
    _pleaseWait : false,
    paymentSelect : false,
    onSubmitPaymentSuccess : false,
    paymentValue : '',
    saveUrl: '',
    successUrl: '',

    /**
     * Add listeners to provided objects, if any
     * @param orderForm - form of the order submission
     * @param orderFormSubmit - element for the order form submission (optional)
     * @param paymentSelect - dropdown with available shipping methods (optional)
     * @param paymentSubmitForm - form of shipping method submission (optional, requires paymentSelect)
     * @param paymentResultId - element where to update results of shipping ajax submission (optional, requires paymentSubmitForm)
     */
    initialize : function(orderForm, orderFormSubmit, paymentSelect, paymentSubmitForm, paymentResultId, paymentSubmit)
    {
        if (!orderForm) {
            return;
        }
        this.form = orderForm;
        if (orderFormSubmit) {
            this.formSubmit = orderFormSubmit;
            this.saveUrl = this.form.action;
            Event.observe(orderFormSubmit, 'click', this._submitOrder.bind(this));
        }

        if (paymentSubmitForm && paymentSelect) {
            this.paymentSelect = paymentSelect;
            Event.observe(paymentSelect, 'change', this._submitPayment.bindAsEventListener(this, paymentSubmitForm.action, paymentResultId));
            //this._updateOrderSubmit(false);
        } else {
            this._canSubmitOrder = true;
        }
        this.onSave = this.nextStep.bindAsEventListener(this);
    },

    /**
     * Register element that should show up when ajax request is in progress
     * @param element
     */
    addPleaseWait : function(element)
    {
        if (element) {
            this._pleaseWait = element;
        }
    },

    /**
     * Dispatch an ajax request of shipping method submission
     * @param event
     * @param url - url where to submit shipping method
     * @param resultId - id of element to be updated
     */
    _submitPayment : function(event, url, resultId)
    {
        if (this.paymentSelect && url && resultId) {
            this._updateOrderSubmit(true);
            if (this._pleaseWait) {
                this._pleaseWait.show();
            }
			this._getPaymentValue();
            if ('' != this.paymentValue) {
                new Ajax.Updater(resultId, url, {
                    parameters: {'payment[method]':this.paymentValue},
                    onComplete: function() {
                        if (this._pleaseWait) {
                            this._pleaseWait.hide();
                        }
                    }.bind(this),
                    onSuccess: this._onSubmitPaymentSuccess.bind(this),
                    evalScripts: true
                });
            }
        }
    },
	/**
	 *return payment value
	 */
    _getPaymentValue : function()
	{
	  var paymentValue;
	  this.paymentSelect.select('input').each(
	    function(node){
		  if(node.checked)
		  {
		     paymentValue = node.value;
		  }
		});
	   this.paymentValue = paymentValue;
	},
    /**
     * Attempt to submit order
     */
    _submitOrder : function()
    {
		if (this._pleaseWait) {
            this._pleaseWait.show();
        }
		var request = new Ajax.Request(
	            this.saveUrl,
	            {
	                method:'post',
	                parameters:'',
	                onComplete: this.onComplete,
	                onSuccess: this.onSave
	            }
	        );
		return false;
    },

    /**
     * Explicitly enable order submission
     */
    _onSubmitPaymentSuccess : function()
    {
        this._updateOrderSubmit(false);
        if (this.onSubmitPaymentSuccess) {
            this.onSubmitPaymentSuccess();
        }
    },

    /**
     * Check/Set whether order can be submitted
     * Also disables form submission element, if any
     * @param shouldDisable - whether should prevent order submission explicitly
     */
    _updateOrderSubmit : function(shouldDisable)
    {
        var isDisabled = shouldDisable || !this.paymentSelect || '' == this.paymentValue;
        this._canSubmitOrder = !isDisabled;
        if (this.formSubmit) {
            this.formSubmit.disabled = isDisabled;
            this.formSubmit.removeClassName('no-checkout');
            this.formSubmit.setStyle({opacity:1});
            if (isDisabled) {
                this.formSubmit.addClassName('no-checkout');
                this.formSubmit.setStyle({opacity:.5});
            }
        }
    },    
    nextStep: function(transport){
        if (transport && transport.responseText) {
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
            }
            if (response.redirect) {
                location.href = response.redirect;
                return;
            }
            if (response.success) {
                this.isSuccess = true;
                window.location=this.successUrl;
            }
            else{
                var msg = response.error_messages;
                if (typeof(msg)=='object') {
                    msg = msg.join("\n");
                }
                if (msg) {
                    alert(msg);
                }
            }
        }
    },

    isSuccess: false
};
